package com.spi.service;

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;

@Service
public class ImageService {

    // 高质量压缩方法 - 保持OCR识别率
    public byte[] compressImageForOCR(MultipartFile file, float quality) throws IOException {
        if (quality < 0.5f) {
            throw new IllegalArgumentException("质量参数不能低于0.5以保证OCR识别率");
        }

        // 读取原始图片
        BufferedImage image = ImageIO.read(file.getInputStream());

        // 优化DPI - OCR通常对300DPI以上的图片识别效果更好
        BufferedImage optimizedImage = optimizeDPI(image, 300);

        // 创建压缩后的输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("JPEG");
        ImageWriter writer = writers.next();
        ImageWriteParam param = writer.getDefaultWriteParam();

        // 设置压缩质量
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(quality); // 0.7f-0.9f之间通常是OCR的最佳范围

        try (ImageOutputStream ios = ImageIO.createImageOutputStream(baos)) {
            writer.setOutput(ios);
            writer.write(null, new IIOImage(optimizedImage, null, null), param);
        }

        String outputPath = "D:\\image\\after\\a.jpg" ;
        // 将压缩后的图片写入本地文件
        if (outputPath != null && !outputPath.isEmpty()) {
            File outputFile = new File(outputPath);
            // 确保目录存在
            File parentDir = outputFile.getParentFile();
            if (parentDir != null && !parentDir.exists()) {
                parentDir.mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(outputFile) ;
            baos.writeTo(fos);
            System.out.println("图片已成功写入: " + outputPath);
            fos.close();
        }


        return baos.toByteArray();
    }

    // 优化图片DPI
    private BufferedImage optimizeDPI(BufferedImage image, int dpi) {
        // 如果需要调整DPI，可以在这里添加代码
        // 注意：直接调整DPI不会改变图片尺寸，但会影响OCR对文字大小的判断
        return image;
    }

    // 保持宽高比的智能压缩
    public byte[] smartCompression(MultipartFile file, int maxWidth, int maxHeight, float quality) throws IOException {
        if (quality < 0.6f) {
            throw new IllegalArgumentException("OCR识别建议质量不低于0.6");
        }

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        Thumbnails.of(file.getInputStream())
                .scale(1.0) // 初始比例
                .outputQuality(quality)
                .outputFormat("JPEG")
                .toOutputStream(outputStream);

        // 如果压缩后的文件仍然太大，可以考虑按比例缩小尺寸
        byte[] compressedBytes = outputStream.toByteArray();
        if (compressedBytes.length > 1024 * 1024) { // 如果大于1MB
            outputStream.reset();
            Thumbnails.of(file.getInputStream())
                    .width(maxWidth)
                    .height(maxHeight)
                    .outputQuality(quality)
                    .outputFormat("JPEG")
                    .toOutputStream(outputStream);
            compressedBytes = outputStream.toByteArray();
        }

        return compressedBytes;
    }
}
